# @Author   : tan90
# @Time     : 2025/1/25 08:37
import socket
from machine import Pin

led = Pin(2, Pin.OUT)

# 创建 UDP 套接字
def create_udp_socket(ip, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((ip, port))
    print(f"UDP 服务器已启动，监听 {ip}:{port}")
    return sock


# 监听并接收数据
def udp_listen(sock):
    while True:
        data, addr = sock.recvfrom(1024)
        print(f"收到来自 {addr} 的数据: {data.decode()}")
        if data == b"ON":
            led.on()
        elif data == b"OFF":
            led.off()
        sock.sendto(b"Received: " + data, addr)

if __name__ == '__main__':
    udp_listen(create_udp_socket('0.0.0.0', 12345))